<?php
/*
 * @Author: your name
 * @Date: 2020-11-01 23:52:41
 * @LastEditTime: 2020-12-07 15:28:01
 * @LastEditors: Please set LastEditors
 * @Description: IP处理
 * @FilePath: /special/application/adminapiv3/service/module_manage/netfilter/PortProcessService.php
 */
namespace app\adminapiv3\service\module_manage\netfilter;

class PortProcessService
{
    /**
     * @name: ip数据输入处理
     * @Param: 
     * @Description: 
     * @Author: foo
     * @Date: 2020-11-02 00:42:11
     */
    public static function inputProcess ($src_port, $dest_port)
    {
        $src_port_a = self::process($src_port);
        $dest_port_a = self::process($dest_port);

        $return = [];
        foreach ($src_port_a as $sport_v)
        {
            foreach ($dest_port_a as $dport_v)
            {
                $temp['src_port_s'] = $sport_v[0];
                $temp['src_port_e'] = $sport_v[1];
                $temp['dest_port_s'] = $dport_v[0];
                $temp['dest_port_e'] = $dport_v[1];

                $return[] = $temp;
            }
        }
        return $return;
    }

    private static function process($port)
    {
        $port = explode(',', strtolower($port));
        foreach ($port as $sv)
        {
            $sv_a = explode(':', $sv);
            if (count($sv_a) == 1)
            {
                $sv_a = $sv_a[0] == 'any' ? [0,65535] : [$sv_a[0],$sv_a[0]];
            }

            $return[] = $sv_a;
        }

        return $return;
    }

    /**
     * @name: 数据输出处理
     * @Param: 
     * @Description: 
     * @Author: foo
     * @Date: 2020-11-02 13:37:08
     */
    public static function outProcess ($port_s)
    {
        $port_a = array_unique(explode(',', $port_s));

        foreach ($port_a as $k => $port)
        {
            $porta = explode(':', $port);
            switch ($porta)
            {
                case $porta[0] == $porta[1] :
                    $port_a[$k] = $porta[0];
                    break;
                case $porta[0] <= 0 && $porta[1] >= 65535 :
                    $port_a[$k] = 'any';
                    break;
                default:
                    $port_a[$k] = $porta[0] . ':' . $porta[1];
            }
        }

        $port_s = implode(',', $port_a);

        return $port_s;

    }
}
